package logic

import (
	"context"
	"fmt"
	"product/model/cache"
	"product/model/mysql"
	"product/pkg"
	"product/productrpc/internal/svc"
	"product/productrpc/productrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UdatePasswordLogic {
	return &UdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 重置密码
func (l *UdatePasswordLogic) UdatePassword(in *productrpc.UdatePasswordRequest) (*productrpc.UdatePasswordResponse, error) {
	// todo: add your logic here and delete this line
	var userd mysql.User
	mysql.DB.Debug().Where("account=?", in.Account).Find(&userd)

	if userd.ID == 0 {
		return nil, fmt.Errorf("该用户不存在")
	}

	result, _ := cache.Rdb.Get(l.ctx, "SendSms"+in.Account).Result()
	if result != in.SendCode {
		return nil, fmt.Errorf("验证码输入错误")
	}

	if in.Password != in.Newpassword {
		return nil, fmt.Errorf("修改两次密码输入不一致")
	}
	if pkg.Md5(in.Password) == userd.Password {
		return nil, fmt.Errorf("新旧密码一致")
	}
	userd.Password = pkg.Md5(in.Password)

	mysql.DB.Debug().Updates(&userd)
	return &productrpc.UdatePasswordResponse{
		Id: int64(userd.ID),
	}, nil
}
